package net.chrone.quickpayapi.task;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import net.chrone.quickpayapi.api.CiticApi;
import net.chrone.quickpayapi.model.PayforTxn;
import net.chrone.quickpayapi.service.PayforService;
import net.chrone.quickpayapi.util.Constant;

/**
 * 单笔付款交易查询结果
 * @author Jerry
 *
 */
@Component
public class PayforQueryTask {
	
	private final  Logger logger = Logger.getLogger(getClass());
	
	@Autowired
	private PayforService payforService;
	
	@Scheduled(cron="0 0/2 * * * ?")
	public void query(){
		logger.debug("查询高汇通付款中交易");
		List<PayforTxn> txns = payforService.find(Constant.CHNL_CODE_CITIC,Constant.PAYFOR_ST_PAING);
		if(txns!=null&&txns.size()>0){
			String currentTs = System.currentTimeMillis()+"";
			int i=0;
			for(PayforTxn txn:txns){
				String respInfo = CiticApi.payforQuery(txn,currentTs+(i++));
				String code = respInfo.split(":")[0];
				String info = respInfo.split(":")[1];
				if(StringUtils.isNotEmpty(respInfo)){
					if("000000".equals(code)){//000000是交易成功;PB0098是交易失败;PB0099是处理中 
						txn.setPaySt(Constant.PAYFOR_ST_PAID_SUCCESS);
					}else if("PB0098".equals(code)){
						txn.setPaySt(Constant.PAYFOR_ST_FAIL);
					}else{
						continue;
					}
					txn.setModified(new Date());
					txn.setRespCode(code);
					txn.setRespDesc(info);
					payforService.updateByPrimaryKey(txn);//修改交易状态
				}
			}
		}
	}
}
